package com.pisces.tool.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlUtil {

	public static final String escapeJSTag(String input) {
		if (input == null) {
			input = "";
			return input;
		}
		input = input.trim().replaceAll("\t", "\\\\t");
		input = input.trim().replaceAll("\n", "\\\\n");
		input = input.trim().replaceAll("\r", "\\\\r");
		input = input.trim().replaceAll("\"", "\\\\\"");
		return input;
	}
	
	public static final String escapeHTMLTag(String input) {
		boolean b = true;
		if (input == null) {
			input = "";
			return input;
		}
		input = input.trim().replaceAll("&", "&amp;");
		input = input.trim().replaceAll("<", "&lt;");
		input = input.trim().replaceAll(">", "&gt;");
		input = input.trim().replaceAll("\t", "    ");
		input = input.trim().replaceAll("\r\n", "\n");
		input = input.trim().replaceAll("\n", "\n\r");
		//input = input.trim().replaceAll("  ", " &nbsp;");
		input = input.trim().replaceAll("'", "&#39;");
		input = input.trim().replaceAll("\\\\", "&#92;");
		while (input.indexOf('\"') > -1) {
			if (b) {
				input = input.replaceFirst("\"", "“");
				b = false;
			} else {
				input = input.replaceFirst("\"", "”");
				b = true;
			}
		}
		return input;
	}
	
	/**
	 * 获取html字符串中的图片地址
	 * 
	 * @param htmlStr 输入的字符串
	 * @return List<String> 返回图片地址列表
	 */
	public static List<String> getImgStr(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();
		String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); // 匹配src
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	/**
	 * 移除html字符串中的图片
	 * 
	 * @param htmlStr 输入的字符串
	 * @return 返回移除图片后的字符串
	 */
	public static String removeImgStr(String htmlStr) {
		Pattern p_image;
		Matcher m_image;
		String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			htmlStr = htmlStr.replace(m_image.group(0), "");
		}
		return htmlStr;
	}

	/**
	 * 移除所有html标记
	 * 
	 * @param htmlStr
	 *            输入的字符串
	 * @return 返回移除html标记后的字符串
	 */
	public static String removeHtmlStr(String htmlStr) {
		Pattern p_image;
		Matcher m_image;
		String regEx_img = "<[^>]*>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			htmlStr = htmlStr.replace(m_image.group(0), "");
		}
		return htmlStr;
	}
}
